package com.example.vendingmachine.service.impl;

import com.example.vendingmachine.dto.PaymentRequestDTO;
import com.example.vendingmachine.dto.PaymentQuery;
import com.example.vendingmachine.dto.PaymentStatsDTO;
import com.example.vendingmachine.entity.Order;
import com.example.vendingmachine.entity.PaymentRecord;
import com.example.vendingmachine.mapper.PaymentMapper;
import com.example.vendingmachine.service.OrderService;
import com.example.vendingmachine.service.PaymentService;
import com.example.vendingmachine.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@RequiredArgsConstructor
public class PaymentServiceImpl implements PaymentService {

    private final PaymentMapper paymentMapper;
    private final OrderService orderService;

    @Override
    public PageInfo<PaymentRecord> listPayments(PaymentQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return new PageInfo<>(paymentMapper.selectList(query));
    }

    @Override
    public PaymentRecord getPaymentById(Long id) {
        PaymentRecord payment = paymentMapper.selectById(id);
        if (payment == null) {
            throw new BusinessException("支付记录不存在");
        }
        return payment;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PaymentRecord createPayment(PaymentRequestDTO request) {
        // 检查订单是否存在
        Order order = orderService.getOrderById(request.getOrderId());
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 检查订单状态
        if (!"PENDING".equals(order.getStatus())) {
            throw new BusinessException("订单状态不正确");
        }

        // 检查是否已存在支付记录
        PaymentRecord existPayment = paymentMapper.selectByOrderId(request.getOrderId());
        if (existPayment != null) {
            throw new BusinessException("订单已存在支付记录");
        }

        // 创建支付记录
        PaymentRecord payment = new PaymentRecord();
        payment.setPaymentNo(generatePaymentNo());
        payment.setOrderId(order.getId());
        payment.setOrderNo(order.getOrderNo());
        payment.setAmount(order.getAmount());
        payment.setPayType(request.getPayType());
        payment.setStatus("PENDING");

        paymentMapper.insert(payment);
        return payment;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlePaymentCallback(String payType, String transactionId, String status) {
        PaymentRecord payment = paymentMapper.selectByTransactionId(transactionId);
        if (payment == null) {
            throw new BusinessException("支付记录不存在");
        }

        // 更新支付记录状态
        payment.setStatus(status);
        payment.setPayTime(LocalDateTime.now());
        paymentMapper.update(payment);

        // 如果支付成功，更新订单状态
        if ("SUCCESS".equals(status)) {
            orderService.updateOrderStatus(payment.getOrderId(), "PAID");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refundPayment(Long id) {
        PaymentRecord payment = getPaymentById(id);
        
        // 检查支付状态
        if (!"SUCCESS".equals(payment.getStatus())) {
            throw new BusinessException("支付状态不正确");
        }

        // 更新支付记录状态
        payment.setStatus("REFUNDING");
        paymentMapper.update(payment);

        // TODO: 调用第三方支付平台退款接口
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleRefundCallback(String payType, String transactionId, String status) {
        PaymentRecord payment = paymentMapper.selectByTransactionId(transactionId);
        if (payment == null) {
            throw new BusinessException("支付记录不存在");
        }

        // 更新支付记录状态
        payment.setStatus("REFUNDED");
        payment.setRefundTime(LocalDateTime.now());
        paymentMapper.update(payment);

        // 更新订单状态
        orderService.updateOrderStatus(payment.getOrderId(), "REFUNDED");
    }

    @Override
    public PaymentStatsDTO getPaymentStats(PaymentQuery query) {
        return paymentMapper.selectStats(query);
    }

    /**
     * 生成支付流水号
     */
    private String generatePaymentNo() {
        return "PAY" + DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
                .format(LocalDateTime.now());
    }
} 